<?php

namespace App\Admin\Controllers;

use App\Models\Productline;
use App\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

use App\Models\Role;

class UserController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('员工')
            ->description('description')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('员工')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('员工')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('员工')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User);
        $grid->model()->with(['roles', 'productlines'])->orderBy('id', 'desc');

        $grid->model()->orderBy('id', 'desc');

        $grid->id('Id');
        $grid->column('avatar', '头像')->display(function () {
            if (!$this->avatar) {
                return '';
            }
            $url = \Storage::url($this->avatar);
            return sprintf('<a href="%s" target="_blank"><img src="%s" class="img-sm" /></a>', $url, $url);
        });
        $grid->name('用户名');
        $grid->realName('真实姓名');
        $grid->phone('手机');
        $grid->column('sex', '性别')->display(function () {
            return $this->sexText;
        });
        $grid->roles('角色')->pluck('name')->label('primary');
        $grid->productlines('生产线')->pluck('name')->label('info');

        $grid->column('注册时间')->display(function () {
            return $this->regtime ? $this->regtime->format('Y-m-d H:i:s') : '';
        });

        $grid->filter(function ($filters) {
            $filters->where(function ($query) {
                return $query->whereHas('productlines', function ($query) {
                    return $query->where('productlineId', $this->input);
                });
            }, '生产线', 'productline')->select(Productline::pluck('name', 'id'));
            $filters->where(function ($query) {
                return $query->whereHas('roles', function ($query) {
                    return $query->where('roleId', $this->input);
                });
            }, '角色', 'role')->select(Role::pluck('name', 'id'));
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->id('Id');
        $show->name('Name');
        $show->email('Email');
        $show->email_verified_at('Email verified at');
        $show->password('Password');
        $show->remember_token('Remember token');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $model = new User();
        $form = new Form($model);
        $table = $model->getTable();

        $form->text('name', '用户名')->rules(['required', Rule::unique($table)->ignore(\Route::current()->parameter('user'))]);
        $form->text('realName', '真实姓名')->rules('required');
        $form->image('avatar', '头像');
        $form->text('phone', '手机');
        $form->radio('sex', '性别')->options(User::$sexText);
        $form->password('password', '密码')->rules('required|confirmed')
            ->default(function ($form) {
                return $form->model()->password;
            });
        $form->password('password_confirmation', '确认密码')->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });
        $form->ignore(['password_confirmation']);

        $form->checkbox('productlines', '所属生产线')->options(Productline::pluck('name', 'id'));
        $form->checkbox('roles', '分配角色')->options(Role::pluck('name', 'id'));

        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });

        return $form;
    }

    public function selectJson(Request $request)
    {
        $q = $request->q;
        if (!$q)
        {
            return [];
        }
        $users = User::where(function ($query) use ($q) {
            $query->where("name", "like", "%{$q}%")->orWhere("realName", "like", "%{$q}%");
        })->paginate(null, ['id', 'name', 'realName']);

        foreach ($users as &$user)
        {
            $user->text = sprintf("%s(%s)", $user->name, $user->realName);
        }

        return $users;
    }
}
